#include<stdio.h>  
#include<unistd.h>  
#include<sys/types.h>  
#include<sys/socket.h>  
#include<netinet/in.h>  
#include<arpa/inet.h>  
#include<time.h>  
#include<netdb.h>  
#include<stdlib.h>  
#include<string.h>  
#define PORT 1234  
#define BACKLOG 5  
  
int main()  
{  
    int listenfd, connectfd;  
    struct sockaddr_in server;  
    struct sockaddr_in client;  
    socklen_t addrlen;  
      
    time_t t;  
    t=time(NULL);  
      
    FILE *fd=fopen("/root/saveIP","a");  
    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)  
    {  
        perror("socket() error.");  
       return 0;  
    }  
  
    int opt = SO_REUSEADDR;  
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));  
  
    bzero(&server, sizeof(server));  
    server.sin_family = AF_INET;  
    server.sin_port = htons(PORT);  
    server.sin_addr.s_addr = htonl(INADDR_ANY);  
    if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1)  
    {  
        perror("bind() error.");  
            return 0;  
  
    }  
    if(listen(listenfd, BACKLOG) == -1)  
    {  
        perror("listen() error.");  
        return 0;  
    }  
  
    addrlen = sizeof(client);  
    if((connectfd = accept(listenfd, (struct sockaddr *)&client, &addrlen )) == -1)  
    {  
            perror("accept() error.");  
        return 0;  
    }  
      
    printf("客户端IP：%s.  ",inet_ntoa(client.sin_addr));  
    printf("当前时间： %s\n",ctime(&t));  
    send(connectfd,(time_t *)&t,sizeof(time_t),0);  
    fprintf(fd,"%s   %s\n",inet_ntoa(client.sin_addr),ctime(&t));  
    fclose(fd);  
      
    return 1;  
}     

